﻿using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Input;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;


namespace D.B.Data.Common
{
    public class JwtTools
    {

    

        public string JwtNewString(IConfiguration configuration,string uid, LoginDTO user)
        {

            //2.生成JWT
            //Header,选择签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            //Payload，存放用户信息，下面我们放了一个用户id
            var claims = new[]
            {
                  new Claim(type: JwtRegisteredClaimNames.Sub,uid),
                  new Claim(type: ClaimTypes.Name,user.UserName),
                  new Claim(type: ClaimTypes.Role,string.Join(',',user.RoleId)),
                  new Claim(type: "Id",user.Id.ToString()),
                  new Claim(type: "DeptId",user.DeptId.ToString()),
            };

         

            var secretByte= Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]);
            var signingKey = new SymmetricSecurityKey(secretByte);
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);

            var Token = new JwtSecurityToken
             (
             issuer: configuration["JwtSettings:Issuer"],
             audience: configuration["JwtSettings:Audience"],
             claims: claims,
             notBefore: DateTime.UtcNow,
             expires: DateTime.UtcNow.AddDays(1),
             signingCredentials
             );



            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
             return TokenStr;
           
        }
    }
}
